var appId = 'wx294c72039771cba8';
var hostUrl = "https://api.readerday.com/v1/";
// var hostUrl = "http://testmerchant.readerday.com/v1/";
var shareUrl = "https://merchant.readerday.com/";
// var shareUrl = "http://testwxmerchant.readerday.com/";
var userId = '10000'
var date = new Date().getTime()
var imgHosturl = "http://img.readerday.com/cover/";
var imgFaceurl = "http://img.readerday.com/face/";
var slogenFont = ["蜜读 | 解读全球经典好书", "蜜读 | 传播全人类共有的知识和观点", "蜜读 | 书,是人生的第一滴蜜", "蜜读 | 名师解读,30分钟即可阅读一本书", "蜜读 | 留存全书精髓,过滤90%的无效信息", "蜜读 | 严选国内外经典好书,告别低质阅读", "蜜读 | 帮你化繁为简,降低阅读难度"]
var weixinData = null;
var openId = window.sessionStorage.getItem("openId");
var authorizerAppid = window.sessionStorage.getItem("authorizerAppid");
var history

if (GetQueryString('merchantId') != null) {
    var merchant = GetQueryString('merchantId');
    localStorage.setItem('merchantId', merchant)
}
var merchantId = localStorage.getItem('merchantId')
var token = window.sessionStorage.getItem("token");
token = token ? token : "0";
var userVip = window.sessionStorage.getItem("userVip");
userVip = userVip ? JSON.parse(userVip) : {};
var splitCode = "?code".indexOf(window.location.href) == -1 ? "&code" : "?code";
var Cappid
if (GetQueryString('appid') != null) {
    Cappid = GetQueryString('appid')
    localStorage.setItem('Cappid', GetQueryString('appid'));
}
var relink = shareUrl + "auth.html?url=" + window.location.href.split(splitCode)[0]
var authappid = localStorage.getItem('Cappid') == 'undefined' ? sessionStorage.getItem("authorizerAppid") : localStorage.getItem('Cappid')


if(localStorage.getItem('Cappid') == 'undefined'){
    if (window.location.href.split(splitCode)[0].substring(window.location.href.split(splitCode)[0].length - 4) == 'html') {
        relink = shareUrl + "auth.html?url=" +window.location.href.split(splitCode)[0]  + '&home=1&merchantId=' + merchantId
    } else {
        relink = shareUrl + "auth.html?url=" +window.location.href.split(splitCode)[0]  + '&home=1&merchantId=' + merchantId;
    }
}else {
    if (window.location.href.split(splitCode)[0].substring(window.location.href.split(splitCode)[0].length - 4) == 'html') {
        relink = shareUrl + "openAuth.html?url=" +window.location.href.split(splitCode)[0] + '&home=1&merchantId=' + merchantId + '&appid=' + authappid;
    } else {
        relink = shareUrl + "openAuth.html?url=" +window.location.href.split(splitCode)[0] +  '&home=1&merchantId=' + merchantId  + '&appid=' + authappid;
    }
}

var payOpenId = localStorage.getItem("payOpenId")=="undefined"? null : localStorage.getItem("payOpenId");
var currentUrl = location.href  //当前页面地址

function getToken(fn) {
    var loginUrl;
    //分销商未绑定服务号登录
    if (Cappid == undefined || Cappid == 'undefined') {
        loginUrl = hostUrl + "merchant/jssgin?url=" + encodeURIComponent(window.location.href.split("#")[0]);
    } else { //C端用户
        window.localStorage.setItem('Cappid', Cappid)
        loginUrl = hostUrl + "merchant/jssgin?url=" + encodeURIComponent(window.location.href.split("#")[0]) + "&authorizerAppid=" + Cappid + "&merchantId=" + merchantId;
    }
    $.ajax({
        url: loginUrl,
        dataType: "json",
        success: function (data) {
            var shareData = {};
            shareData.share = data.data;
            after(shareData);
        }
    });

    if (!!!window.sessionStorage.getItem("openId")) {

        var urlData = $.url().param();
        var Acode;
        if (typeof urlData.code == 'string') {
            Acode = urlData.code;
        } else {
            Acode = urlData.code[urlData.code.length - 1];

        }
        window.sessionStorage.setItem("weixinData", '');
        /*
            授权链接：
          1没有Cappid也没有商户id-----------分销商登录
          2有商户id没有Cappid -----------分销商未绑定服务号C端用户登录
          3有Cappid并且有商户id-----------分销商绑定服务号C端用户登录
          */
        if ((Cappid == undefined || Cappid == 'undefined' || Cappid==null) && (merchantId == undefined || merchantId == 'undefined')) { //没有Cappid也没有商户id-----------分销商登录
            localStorage.setItem('Cappid', undefined)//存下商户id
            $.ajax({
                url: hostUrl + "merchant/login?code=" + Acode +"&merchantId=" + merchantId,
                async: false,
                success: function (data) {
                    console.log(data)
                    window.sessionStorage.setItem("weixinData", JSON.stringify(data));
                    openId = data.data.openId;
                    localStorage.setItem('merchantId', data.data.openId)//存下商户id

                    token = data.data.token;
                    if (data.data.vip) {
                        userVip.type = 1
                        userVip.data = data.data.vip
                    } else {
                        userVip.type = -1;
                    }
                    window.sessionStorage.setItem("userVip", JSON.stringify(userVip));
                    window.sessionStorage.setItem("authorizerAppid", data.data.authorizerAppid);
                    window.sessionStorage.setItem("openId", data.data.openId);
                    window.sessionStorage.setItem("token", data.data.token);
                    window.sessionStorage.setItem("subscribe", data.data.subscribe);

                    //交换token
                    fn();
                     location.reload()
                },
                error: function () {
                    console.info('ajax登录调用出错了');
                }
            });

            //
        } else if ((Cappid == undefined || Cappid == 'undefined') && merchantId) { // 有商户id没有Cappid --分销商未绑定服务号C端用户登录
            localStorage.setItem('Cappid', undefined)
            $.ajax({
                url: hostUrl + "merchant/login?code=" + Acode + "&merchantId=" + merchantId,
                async: false,
                success: function (data) {
                    window.sessionStorage.setItem("weixinData", JSON.stringify(data));

                    openId = data.data.openId;
                    token = data.data.token;
                    if (data.data.vip) {
                        userVip.type = 1
                        userVip.data = data.data.vip
                    } else {
                        userVip.type = -1;
                    }
                    window.sessionStorage.setItem("userVip", JSON.stringify(userVip));
                    window.sessionStorage.setItem("authorizerAppid", data.data.authorizerAppid);
                    window.sessionStorage.setItem("openId", data.data.openId);
                    window.sessionStorage.setItem("token", data.data.token);
                    window.sessionStorage.setItem("subscribe", data.data.subscribe);

                    fn();
                     location.reload()
                },
                error: function () {
                    console.info('ajax登录调用出错了');
                }
            });
        } else if (Cappid && merchantId) {//有Cappid并且有商户id-----------分销商绑定服务号C端用户登录
            $.ajax({
                url: hostUrl + "merchant/login?code=" + Acode + "&authorizerAppid=" + Cappid + "&merchantId=" + merchantId,
                async: false,
                success: function (data) {
                    window.sessionStorage.setItem("weixinData", JSON.stringify(data));
                    openId = data.data.openId;
                    token = data.data.token;
                    if (data.data.vip) {
                        userVip.type = 1
                        userVip.data = data.data.vip
                    } else {
                        userVip.type = -1;
                    }
                    window.sessionStorage.setItem("userVip", JSON.stringify(userVip));
                    window.sessionStorage.setItem("openId", data.data.openId);
                    window.sessionStorage.setItem("token", data.data.token);
                    window.sessionStorage.setItem("subscribe", data.data.subscribe);
                    //交换token
                    fn();
                     location.reload()
                },
                error: function () {
                    console.info('ajax登录调用出错了');
                }
            });
        }


    } else {
        openId = window.sessionStorage.getItem("openId");
        token = window.sessionStorage.getItem("token");
        fn();
    }
//授权蜜读平台
       if (Cappid) {
           if(payOpenId == undefined ){
               location.href='../payOpenId.html'
           }
       }

}



function after(dat) {
    wx.config({
        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        appId: dat.share.appId, // 必填，公众号的唯一标识
        timestamp: dat.share.timestamp, // 必填，生成签名的时间戳
        nonceStr: dat.share.nonceStr, // 必填，生成签名的随机串
        signature: dat.share.signature,// 必填，签名，见附录1
        jsApiList: [
            'chooseWXPay','checkJsApi', 'onMenuShareTimeline',
            'onMenuShareAppMessage', 'onMenuShareQQ',
            'onMenuShareWeibo', 'hideMenuItems',
            'showMenuItems', 'hideAllNonBaseMenuItem',
            'showAllNonBaseMenuItem', 'translateVoice',
            'startRecord', 'stopRecord', 'onRecordEnd',
            'playVoice', 'pauseVoice', 'stopVoice',
            'uploadVoice', 'downloadVoice', 'chooseImage',
            'previewImage', 'uploadImage', 'downloadImage',
            'getNetworkType', 'openLocation', 'getLocation',
            'hideOptionMenu', 'showOptionMenu', 'closeWindow',
            'scanQRCode',
            'openProductSpecificView', 'addCard', 'chooseCard',
            'openCard'
        ]
    });
}



function payClick(da, type, product_id, isCloseCurrentPage, backFunc) {

    $.ajax({
        url: hostUrl + "merchant/jssgin?url=" + encodeURIComponent(window.location.href),
        dataType: "json",
        sync:false,
        success: function (data) {
            var att = data.data;
            console.info(att);
            wx.config({
                //debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                appId: att.appId, // 必填，公众号的唯一标识
                timestamp: att.timestamp, // 必填，生成签名的时间戳
                nonceStr: att.nonceStr, // 必填，生成签名的随机串
                signature: att.signature,// 必填，签名
                jsApiList: ['chooseWXPay'] // 必填，需要使用的JS接口列表
            });
        }
    });


    var sign = hex_md5(objKeySort({
        "type": type,
        "token": token,
        "productId": product_id,
        "timestamp": date,
        "merchantId": merchantId
    }))


    $.ajax({
        url: hostUrl + "merchant/wxpay/save",
        type: "post",
        data: {
            "type": type,
            "token": token,
            "timestamp": date,
            "sign": sign,
            "payOpenId": payOpenId,
            "productId": product_id,
            "merchantId": merchantId
        },
        dataType: "json",
        success: function (data) {
            if (data.status == 0) {
                var att = data.data;
                wx.chooseWXPay({
                    timestamp: att.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                    nonceStr: att.nonceStr, // 支付签名随机串，不长于 32 位
                    package: att.packageValue, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
                    signType: att.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                    paySign: att.paySign, // 支付签名
                    success: function (res) {
                        // 支付成功后的回调函数
                        location.reload();
                    },
                    cancel: function (res) {

                    }
                });
            } else {
                alert(data.message);
            }
        },
        error: function () {
            alert("出错了");
        }
    });

}


function shareWx(title, img, desc) {
    var titleStr, bookid, stage, imgStr = img.substring(0, 4);
    if (imgStr == "http") {
        imgUrl = img;
    } else {
        imgUrl = imgHosturl + img;
    }
    var arr = title.split('key=');
    if (arr.length > 1) {
        titleStr = arr[0];
        bookid = arr[1];
        stage = arr[2];
    } else {
        titleStr = title;
    }

    wx.ready(function () {
        //分享朋友圈
        wx.onMenuShareTimeline({
            title: titleStr,
            link: relink,
            imgUrl: imgUrl,// 自定义图标
            trigger: function (res) {
                // 不要尝试在trigger中使用ajax异步请求修改本次分享的内容，因为客户端分享操作是一个同步操作，这时候使用ajax的回包会还没有返回.
                //alert('click shared');
            },
            success: function (res) {
                MtaH5.clickStat("share_button")//用户点击右上角分享按钮
                MtaH5.clickShare('wechat_moments');//统计朋友圈分享
                if (bookid) {
                    if (window.localStorage) {
                        localStorage.setItem('share_activity', bookid + "_" + stage);
                    } else {
                        setCookie('share_activity', bookid + "_" + stage);
                    }
                }
            },
            cancel: function (res) {
                //alert('shared cancle');
            },
            fail: function (res) {
                //alert(JSON.stringify(res));
            }
        });
        //分享到QQ
        wx.onMenuShareQQ({
            title: titleStr,
            desc: desc, // 分享描述
            link: relink,
            imgUrl: imgUrl,// 自定义图标
            type: 'link', // 分享类型,music、video或link，不填默认为link
            dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
            success: function () {
                MtaH5.clickStat("share_button")//用户点击右上角分享按钮
                if (bookid) {
                    if (window.localStorage) {
                        localStorage.setItem('share_activity', bookid + "_" + stage);
                    } else {
                        setCookie('share_activity', bookid + "_" + stage);
                    }
                }
            },
            cancel: function () {
                // 用户取消分享后执行的回调函数
            }
        });
        //分享给好友
        wx.onMenuShareAppMessage({
            title: titleStr,
            desc: desc, // 分享描述
            link: relink,
            imgUrl: imgUrl,// 自定义图标
            type: 'link', // 分享类型,music、video或link，不填默认为link
            dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
            success: function () {

                MtaH5.clickStat("share_button")//用户点击右上角分享按钮
                MtaH5.clickShare('wechat_friend');//统计分享微信好友
                MtaH5.clickStat('haoyouzhulimian', {'sharebutton': 'true'})//漏斗统计
                if (bookid) {
                    if (window.localStorage) {
                        localStorage.setItem('share_activity', bookid + "_" + stage);
                    } else {
                        setCookie('share_activity', bookid + "_" + stage);
                    }
                }
            },
            cancel: function () {
                // 用户取消分享后执行的回调函数
            }
        });
        wx.error(function (res) {
            alert(res.errMsg);
        });
    });

}


function setCookie(name, value) {
    var argv = setCookie.arguments;
    var argc = setCookie.arguments.length;
    var expires = (argc > 2) ? argv[2] : null;
    if (expires != null) {
        var LargeExpDate = new Date();
        LargeExpDate.setTime(LargeExpDate.getTime() + (expires * 1000 * 3600 * 24));
    }
    document.cookie = name + "=" + escape(value) + ((expires == null) ? "" : ("; expires=" + LargeExpDate.toGMTString()));
}

function rand(min, max) {
    return parseInt(Math.random() * (max - min)) + min;
}

function formatSeconds(a) {
    var hh = parseInt(a / 3600);
    if (hh > 0 && hh < 10) {
        hh = "0" + hh;
    }
    else {
        hh = '';
    }
    var mm = parseInt((a - hh * 3600) / 60);
    if (mm < 10) mm = "0" + mm;
    var ss = parseInt((a - hh * 3600) % 60);
    if (ss < 10) ss = "0" + ss;
    var length = hh.length ? (hh + ":" + mm + ":" + ss) : mm + ":" + ss;
    if (a > 0) {
        return length;
    } else {
        return "NaN";
    }
}

Date.prototype.Format = function (formatStr) {
    var str = formatStr;
    var Week = ['日', '一', '二', '三', '四', '五', '六'];

    str = str.replace(/yyyy|YYYY/, this.getFullYear());
    str = str.replace(/yy|YY/, (this.getYear() % 100) > 9 ? (this.getYear() % 100).toString() : '0' + (this.getYear() % 100));

    str = str.replace(/MM/, (this.getMonth() + 1) > 9 ? (this.getMonth() + 1).toString() : '0' + (this.getMonth() + 1));
    str = str.replace(/M/g, this.getMonth());

    str = str.replace(/w|W/g, Week[this.getDay()]);

    str = str.replace(/dd|DD/, this.getDate() > 9 ? this.getDate().toString() : '0' + this.getDate());
    str = str.replace(/d|D/g, this.getDate());

    str = str.replace(/hh|HH/, this.getHours() > 9 ? this.getHours().toString() : '0' + this.getHours());
    str = str.replace(/h|H/g, this.getHours());
    str = str.replace(/mm/, this.getMinutes() > 9 ? this.getMinutes().toString() : '0' + this.getMinutes());
    str = str.replace(/m/g, this.getMinutes());

    str = str.replace(/ss|SS/, this.getSeconds() > 9 ? this.getSeconds().toString() : '0' + this.getSeconds());
    str = str.replace(/s|S/g, this.getSeconds());

    return str;
}

function setCookie(c_name, value, expiredays) {
    var exdate = new Date()
    exdate.setDate(exdate.getDate() + expiredays)
    document.cookie = c_name + "=" + escape(value) +
        ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString())
}

//取回cookie
function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=")
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1
            c_end = document.cookie.indexOf(";", c_start)
            if (c_end == -1) c_end = document.cookie.length
            return unescape(document.cookie.substring(c_start, c_end))
        }
    }
    return ""
}

function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURIComponent(r[2]);
    return null;
}

template.defaults.imports.addUrl = function (value) {
    if (value == null || value == "") {
        return "img/book.png"
    } else {
        return imgHosturl + value
    }
};
template.defaults.imports.totalReadCount = function (value) {
    if (value !== null) {
        value = value.toString();
        if (value.length <= 4) {
            return value;
        } else {
            value = value / 10000;
            return value = value.toFixed(1) + "万"
        }
    }
};
template.defaults.imports.topcolor = function (index) {
    if (index < 3) {
        return index + 1;
    } else {
        return 4;
    }
};

template.defaults.imports.addFaceUrl = function (value) {
    if (value == "" || value == null) {
        return "img/book.png"
    } else {
        if (checkURL(value)) {
            return value;
        } else {
            return imgFaceurl + value
        }
    }
};

function checkURL(str) {
    if (str.match(/(http[s]?|ftp):\/\/[^\/\.]+?\..+\w$/i) == null) {
        return false
    }
    else {
        return true;
    }
}

// 2单本   1书包
function weekTip(text) {
    $("#warn").html(text).show();
    setTimeout(function () {
        $("#warn").hide();
    }, 2000)
}

var Q = Query = {
    getFromURL: function (url, parameter) {
        var index = url.indexOf("?");
        if (index != -1) {
            var parameterString = url.substr(index + 1);
            var reg = new RegExp("(^|&)" + parameter + "=([^&]*)(&|$)", "i");
            var r = parameterString.match(reg);
            if (r != null) {
                return r[2];
            }
        }
        return null;
    },
    get: function (parameter) {
        if (typeof (parameter) == "undefined" || parameter == "") {
            return null;
        }
        var url = window.location.href;
        var index = url.indexOf("?");
        if (index != -1) {
            var parameterString = url.substr(index + 1);
            var reg = new RegExp("(^|&)" + parameter + "=([^&]*)(&|$)", "i");
            var r = parameterString.match(reg);
            if (r != null) {
                return r[2];
            }
        }
        return null;
    },
    getInt: function (parameter, defaultValue) {
        var value = parseInt(this.get(parameter));
        return isNaN(value) ? (typeof(defaultValue) == "undefined" ? 0 : defaultValue) : value;
    },
    getDecoded: function (parameter) {
        return this.decode(this.get(parameter));
    },
    decode: function (srcStr) {
        if (typeof(srcStr) == "undefined") {
            return null;
        }
        return decodeURIComponent(srcStr);
    },
    encode: function (srcStr) {
        if (typeof(srcStr) == "undefined") {
            return null;
        }
        return encodeURIComponent(srcStr);
    },
    getSymbol: function (url) {
        return url.indexOf("?") == -1 ? "?" : "&";
    },
    joinURL: function (url, queryString) {
        return url + this.getSymbol(url) + queryString;
    },
    createQueryString: function (obj) {
        var a = [];
        for (var p in obj) {
            if (typeof(obj[p]) == "function" || obj[p] == null || typeof(obj[p]) == "undefined") continue;
            a.push(p + "=" + obj[p]);
        }
        return a.join("&");
    }
};

function objKeySort(obj) { //排序的函数
    var newkey = Object.keys(obj).sort();
    //先用Object内置类的keys方法获取要排序对象的属性名，再利用Array原型上的sort方法对获取的属性名进行排序，newkey是一个数组
    var newObj = '';//创建一个新的字符串，用于存放排好序的键值对
    for (var i = 0; i < newkey.length; i++) {//遍历newkey数组
        newObj += [newkey[i]] + '' + obj[newkey[i]];//向新创建的对象中按照排好的顺序依次增加键值对
    }
    return newObj + '44543e5367854cfcbb3a867f32fa64a2';//返回排好序的字符串
}